package com.izhengyin.inventoryservice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/inventory")
@Slf4j
public class InventoryController{
    private final InventoryRepository inventoryRepository;
    public InventoryController(InventoryRepository inventoryRepository){
        this.inventoryRepository = inventoryRepository;
        //初始化数据
        this.inventoryRepository.save(new Inventory(1L,10));
        this.inventoryRepository.save(new Inventory(2L,1000));
        this.inventoryRepository.findAll()
                .forEach(System.out::println);
    }
    /**
     * 获取可用的库存
     * @return
     */
    @GetMapping("/{itemId}/availableInventory")
    public int getAvailableInventory(@PathVariable long itemId){
        Inventory inventory = inventoryRepository.getOne(itemId);
        return inventory.getAvailableInventory();
    }

    /**
     * 扣除库存(demo服务不处理并发场景)
     * @param itemId
     */
    @PostMapping("/{itemId}/deduct")
    public boolean deductInventory(@PathVariable long itemId){
        Inventory inventory = inventoryRepository.getOne(itemId);
        if(inventory.getAvailableInventory() <= 0){
            return false;
        }
        //模拟扣除库存延迟
        try {
            Random random = new Random();
            TimeUnit.MILLISECONDS.sleep(50+random.nextInt(50));
        }catch (InterruptedException e){
            log.error(e.getMessage(),e);
        }
        inventory.setAvailableInventory(inventory.getAvailableInventory() - 1);
        inventoryRepository.save(inventory);
        return true;
    }
}
